import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 二值化处理：将图像转换为二值图像（即只有黑白两种颜色）可以去除背景干扰，突出字符。
 * 选择合适的阈值进行二值化很重要。如果字符颜色较深，背景较浅，可以将阈值设置为使深色部分变为黑色，浅色部分变为白色的值。
 */
public class ImageBinarization {
    public static void main(String[] args) {
        try {
            File input = new File("src\\main\\resources\\tess4j\\split\\11.png");
            BufferedImage image = ImageIO.read(input);
            // 阈值范围 [0, 255]
            for (int threshold = 0; threshold < 255; threshold++) {
//                int threshold = 128; // 阈值，可以根据实际情况调整
                BufferedImage binaryImage = binarize(image, threshold);
                File output = new File(input.getParentFile() + "\\33\\二值化\\" + threshold + ".jpg");
                ImageIO.write(binaryImage, "jpg", output);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage binarize(BufferedImage image, int threshold) {
        int width = image.getWidth();
        int height = image.getHeight();
        BufferedImage binaryImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int argb = image.getRGB(x, y);
                int alpha = (argb >> 24) & 0xff;
                int red = (argb >> 16) & 0xff;
                int green = (argb >> 8) & 0xff;
                int blue = argb & 0xff;
                int gray = (int)(0.299 * red + 0.587 * green + 0.114 * blue);
                int newPixel = gray > threshold? 0xFFFFFFFF : 0xFF000000;
                binaryImage.setRGB(x, y, newPixel);
            }
        }
        return binaryImage;
    }
}